<template>
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    draggable
    alignCenter
    class="pt10_self"
    width="1100px"
    @close="closeDialog"
  >
    <div>
      <el-row :gutter="20">
        <!-- 目录树 -->
        <el-col
          :lg="4"
          :md="5"
          :sm="6"
          :xs="24"
          class="mb-[12px] !pr-0 bg-white!"
        >
          <databoard-catalog-tree
            ref="databoardCatalogTreeRef"
            v-model="searchParam.catalogId"
            @node-click="search"
            style="height: 626px !important; overflow-y: auto"
            class="databoard-catalog-tree"
          />
        </el-col>
        <el-col :lg="20" :md="19" :sm="18" :xs="24">
          <div v-if="showSearch" class="search-container">
            <CommonSearch
              :formConfig="searchColumns"
              :inline="true"
              labelWidth="auto"
              formItemWidth="auto"
              :model="searchParam"
              :cols="3"
            >
              <template #after>
                <el-button type="primary" @click="search">
                  <i-ep-search />
                  搜索
                </el-button>
                <el-button @click="handleReset">
                  <i-ep-refresh />
                  重置
                </el-button>
              </template>
            </CommonSearch>
          </div>

          <el-card shadow="never" class="table-container" style="height: 548px">
            <el-table
              ref="dataTableRef"
              v-loading="loading"
              :data="tableData"
              :row-key="rowKey"
              highlight-current-row
              height="460px"
              border
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="55" align="center" />
              <!-- 表格内容操作 -->
              <template v-for="item in tableColumns" :key="item">
                <TableColumn v-if="item.prop && item.isShow" :column="item">
                  <template v-for="slot in Object.keys($slots)" #[slot]="scope">
                    <slot :name="slot" v-bind="scope" />
                  </template>
                </TableColumn>
              </template>
            </el-table>

            <el-pagination
              :background="true"
              :current-page="pageable.pageNum"
              :page-size="pageable.pageSize"
              :page-sizes="[10, 25, 50, 100]"
              :total="pageable.total"
              layout="total, sizes, prev, pager, next, jumper"
              class="mt-[20px]"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </el-card>
        </el-col>
      </el-row>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" :loading="posting" @click="addTemplate"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
    <!-- 列设置 抽屉组件 -->
    <ColSetting
      v-model:col-setting="tableColumns"
      v-model:search-setting="searchColumns"
      @search-handle="(e:boolean) => (showSearch = e)"
    />
  </el-dialog>
</template>

<script setup lang="tsx">
import { useTable, useDictionary } from "@/utils/useTable";
import { ElTable, ElMessage } from "element-plus";

defineOptions({
  name: "SYSWORKBENCHTEMPLATEADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible", "add-template"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  isRadio: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);

watch(
  () => props.visible,
  async (newVal: boolean) => {
    visibleDialog.value = newVal;
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
}

const posting = ref(false);

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});

const databoardCatalogTreeRef = ref();

// 是否显示搜索框
const showSearch = ref(true);

// 搜索参数 设置为响应式
const searchColumns: any = reactive([
  // {
  //   type: "input", // 普通输入框
  //   isShow: true,
  //   inputType: "text", // 类型, text/textarea
  //   label: "看板编号", // 标签文本
  //   fieldName: "databoradCode", // 字段名称
  //   placeholder: "请输入编号", // 提示文字
  //   initValue: "", // 默认值
  // },
  {
    type: "input", // 普通输入框
    isShow: true,
    inputType: "text", // 类型, text/textarea
    label: "看板名称", // 标签文本
    fieldName: "databoradName", // 字段名称
    placeholder: "请输入名称", // 提示文字
    initValue: "", // 默认值
  },
  {
    type: "select",
    label: "看板类型",
    isShow: true,
    fieldName: "databoradType",
    placeholder: "请选择类型",
    initValue: null,
    defaultFirstOption: true,
    optionList: useDictionary("DataBoardType"),
  },
]);

// 接收 columns 并设置为响应式
const tableColumns = reactive([
  { prop: "databoradCode", label: "看板编号", isShow: true, minWidth: "100" },
  { prop: "databoradName", label: "看板名称", isShow: true, minWidth: "100" },
  {
    prop: "catalogName",
    label: "目录名称",
    isShow: true,
    minWidth: "100",
  },
  {
    prop: "databoradType",
    label: "看板类型",
    width: 120,
    isShow: true,
    render: (scope: any) =>
      scope.row.databoradType !== "1" ? (
        <el-tag type="warning">
          {useDictionary("DataBoardType", scope.row.databoradType)}
        </el-tag>
      ) : (
        <el-tag>
          {useDictionary("DataBoardType", scope.row.databoradType)}
        </el-tag>
      ),
  },
  {
    prop: "remarks",
    label: "备注",
    isShow: true,
  },
  // {
  //   prop: "databoradUrl",
  //   label: "看板地址",
  //   isShow: true,
  // },
  // {
  //   prop: "enabled",
  //   label: "是否启用",
  //   width: 120,
  //   isShow: true,
  //   render: (scope: any) =>
  //     scope.row.enabled !== 1 ? (
  //       <el-tag type="info">
  //         {useDictionary("Enabled", scope.row.enabled)}
  //       </el-tag>
  //     ) : (
  //       <el-tag type="success">
  //         {useDictionary("Enabled", scope.row.enabled)}
  //       </el-tag>
  //     ),
  // },
]);

// 请求参数
const requestApi = "/system/databoradinfo/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  databoradCode: "",
  databoradName: "",
  catalogId: "",
  databoradType: "",
};

const deleteParam = {
  api: "/system/databoradinfo/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

function handleReset() {
  databoardCatalogTreeRef.value.reset();
  reset();
}
// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  selections,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

onMounted(() => {
  getTableList();
});

interface Template {
  databoradCode: string;
  databoradName: string;
  id: string;
  catalogName: string;
  databoradType: string;
  databoradUrl: string;
  enabled: string;
}

const rowKey = ref("id");

const dataTableRef = ref<InstanceType<typeof ElTable>>();
function addTemplate() {
  if (!selections.value.length) {
    ElMessage.error("请选择看板");
  } else {
    emit("add-template", toRaw(selections.value));
    emit("change-visible", false);
    dataTableRef.value!.clearSelection();
  }
}

const handleSelectionChange = (selection: any) => {
  if (props.isRadio && selection.length > 1) {
    // if (selection.length > 1) {
    const lastSelect = selection[selection.length - 1];
    dataTableRef.value!.clearSelection();
    // dataTableRef.value!.forEach((row: any) => {
    //   if (row == lastSelect) {
    dataTableRef.value!.toggleRowSelection(lastSelect, true);
    // }
    // });
    // selections.value = [lastSelect];
    // ids.value = selections.value.map((item: any) => item.id);
    // console.log();
    // }
  } else {
    selections.value = selection;
    ids.value = selection.map((item: any) => item.id);
  }
};
</script>
<style lang="scss" scoped>
:deep(.pt10_self .el-dialog__body) {
  max-height: 600px;
  overflow-y: auto;
  padding: 20px !important;
}
.formAuto .el-form-item {
  margin-right: 20px !important;
}
</style>
